import $ from './jquery.min.js';
$(() => {
    // 新增演员
    $("#addHeadActorsBtn").on('click', function () {
        $.ajax({
            url: '/Actors',
            type: 'post',
            data: {
                actorname: $("#addHeadActorsName").val(),
                moviesname: []
            },
            traditional: true,
            success(data) {
                if (data.code == 200) {
                    alert(data.message);
                    console.log(data);
                }
            }
        })
    })



    // 演员列表
    $("#actorList").on('click', function () {
        $.ajax({
            url: '/Actors',
            success({ message, code, actors }) {
                if (code == 200) {
                    // console.log(actors.moviesname);
                    // const movie = [...actors.moviesname].map(movie => `${movie.movieTitle} `)
                    $("#actorTb").html('');
                    const result = actors.map(actor =>
                        `<tr>
                        <td>${actor._id}</td>
                        <td>${actor.actorname}</td>
                        <td>${actor.moviesname.map(movie => movie.movieTitle).join(" ")}</td>
                        <td>
                        <a href="">删除</a>
                        <a href="#headActorsAddMovie">关联电影</a>
                        </td>
                        </tr>`
                    )
                    $("#actorTb").html(result);
                }
            }
        })
    })

    // 关联电影
    $("#actorTb").on('click', 'a', function () {
        if ($(this).text() === '关联电影') {
            $("#addRelationActorsBtn").attr("data-actorId",$(this).parents('tr').find('td:first-child').text());
            $.ajax({
                url: '/Films',
                success({ message, status, films }) {
                    $("#relationMovieList").html('');
                    const result = films.map(movie =>
                        `<input class="form-input" value="${movie._id}" type="checkbox"/>${movie.movieTitle}`
                    )
                    $("#relationMovieList").html(result);
                }
            })
        }
    })

    $("#addRelationActorsBtn").on('click',function() {
        const ids = [];
        [...$("#relationMovieList input")].forEach(item => {
            if (item.checked) {
                ids.push($(item).val());
            }
        });
        $.ajax({
            url: '/Actors',
            type: 'put',
            data: {
                actorId: $("#addRelationActorsBtn").attr("data-actorId"),
                movies: ids
            },
            traditional: true,
            success({message,actors}) {
                alert(message);
            }
        })
    })
})